package com.taotao.search.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.taotao.common.pojo.SearchItem;
import com.taotao.common.pojo.SearchResult;

@Repository
public class SearchDao {
	@Autowired
	private SolrServer solrServer;
	public SearchResult search(SolrQuery query)throws Exception{
		//根据条件查询
		QueryResponse queryResponse = solrServer.query(query);
		//取查询结果
		SolrDocumentList documentList = queryResponse.getResults();
		//封装返回数据
		SearchResult result = new SearchResult();
		result.setRecordCount(documentList.getNumFound());
		//商品列表
		List<SearchItem> itemList = new ArrayList<>();
		for (SolrDocument solrDocument : documentList) {
			SearchItem searchItem = new SearchItem();
			searchItem.setCategory_name((String) solrDocument.get("item_category_name"));
			searchItem.setId(Long.parseLong(solrDocument.get("id").toString()));
			searchItem.setImage((String) solrDocument.get("item_image"));
			searchItem.setPrice(Long.parseLong(solrDocument.get("item_price").toString()));
			searchItem.setSell_point((String) solrDocument.get("item_sell_point"));
			//取高亮显示
			Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
			List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
			String itemTitle = "";
			if(list != null && list.size() > 0){
				itemTitle = list.get(0);
			}else {
				itemTitle = (String) solrDocument.get("item_title");
			}
			searchItem.setTitle(itemTitle);
			itemList.add(searchItem);
		}
		result.setItemList(itemList);
		return result;
	}
}
